import type { STORAGE_MODES } from '@/enum/modules/indicator'
import { selectHomeAnalysis, selectHomeChart } from '@/api/modules/home'

export interface WorkbenchCard {
  name: string
  value: string
  now: number
  nowTime: string
  previous: number
  previousTime: string
  beforePrevious: number
  beforePreviousTime: string
  /** 环比 */
  mom: number
  /** 同比 */
  yoy: number
}

export function useWorkbench() {
  const [loading, setLoading] = useState(false)
  const [cards, setCards] = useShallowState<WorkbenchCard[]>([])
  const [chartData, setChartData] = useShallowState<any[] | null>([])

  async function getCards(timeType: STORAGE_MODES) {
    setLoading(true)
    try {
      const res = await selectHomeAnalysis(timeType)
      // console.log(res.data)
      setCards(res.data || [])
    }
    catch (e) {
      console.warn(e)
    }
    finally {
      setLoading(false)
    }
  }

  async function getCharts(timeType: STORAGE_MODES, value: string) {
    try {
      const { data } = await selectHomeChart(timeType, value)
      setChartData([
        ['时间', ...(data.xaxis?.data || [])],
        ...data.series?.map((item: any) => [item.name, ...(item.data || [])]),
      ])
    }
    catch (e) {
      console.warn(e)
    }
  }

  return {
    loading,
    /** 分析数据 */
    cards,
    /** 图表数据 */
    chartData,
    setChartData,
    /** 获取分析数据 */
    getCards,
    /** 获取图表数据 */
    getCharts,
  }
}
